"""
固件下载程序主入口
"""
import sys
import os
import atexit
from PyQt5.QtWidgets import QApplication, QMessageBox
from PyQt5.QtGui import QIcon

# 添加当前目录到路径，确保可以导入模块
current_dir = os.path.dirname(os.path.abspath(__file__))
if current_dir not in sys.path:
    sys.path.append(current_dir)

# 设置DLL搜索路径，确保能找到libopenblt.dll
app_dir = os.path.join(current_dir, 'app')
os.environ['PATH'] = app_dir + os.pathsep + os.environ.get('PATH', '')

# 添加模块目录到Python路径
sys.path.append(os.path.join(current_dir, 'app', 'ui'))
sys.path.append(os.path.join(current_dir, 'app', 'model'))
sys.path.append(os.path.join(current_dir, 'app', 'controller'))

def check_openblt_library():
    """检查OpenBLT库是否可用"""
    try:
        import openblt
        print(f"OpenBLT库版本: {openblt.version_get_string()}")
        return True
    except ImportError as e:
        print(f"导入OpenBLT库失败: {str(e)}")
        return False
    except Exception as e:
        print(f"加载OpenBLT库时出错: {str(e)}")
        return False

# 导入应用程序组件
try:
    from app.ui.main_window import MainWindow
    from app.model.bootloader import BootloaderModel
    from app.controller.main_controller import MainController
except ImportError as e:
    print(f"导入应用程序组件失败: {str(e)}")
    sys.exit(1)

def main():
    """主程序入口"""
    # 检查OpenBLT库
    if not check_openblt_library():
        app = QApplication(sys.argv)
        QMessageBox.critical(None, "错误", "无法加载OpenBLT库，请确保libopenblt.dll在app目录中。")
        sys.exit(1)
    
    # 创建Qt应用程序
    app = QApplication(sys.argv)
    app.setApplicationName("MicroBoot")
    
    # 设置应用程序图标
    # app.setWindowIcon(QIcon("path/to/icon.png"))
    
    # 创建MVC组件
    view = MainWindow()
    model = BootloaderModel()
    controller = MainController(model, view)
    
    # 初始化控制器
    controller.initialize()
    
    # 注册退出时的清理函数
    atexit.register(controller.terminate)
    
    # 显示主窗口
    view.show()
    
    # 运行应用程序事件循环
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()
